package cn.kow.kmall.service.impl;

import cn.kow.kmall.common.enums.KmallResultEnum;
import cn.kow.kmall.core.constant.KmallStatusConstant;
import cn.kow.kmall.core.exception.ServiceException;
import cn.kow.kmall.dao.OrderRefundRepository;
import cn.kow.kmall.pojo.entity.OrderRefund;
import cn.kow.kmall.service.OrderRefundService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Random;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2020-05-06 19:48
 * @Modified By:
 */
@Service("orderRefundService")
public class OrderRefundServiceImpl implements OrderRefundService {

    @Autowired
    private OrderRefundRepository orderRefundRepository;

    @Override
    public OrderRefund create(OrderRefund orderRefund) {
        String refundNo = createOrderRefundNo();
        orderRefund.setRefundNo(refundNo);
        orderRefund.setCreateTime(new Date());
        orderRefund.setStatus(KmallStatusConstant.NORMAL);
        return orderRefundRepository.create(orderRefund);
    }

    /**
     * 获取退款单
     * @param refundNo 退款单号
     * @return 结果
     */
    @Override
    public OrderRefund getByRefundNo(String refundNo) {
        OrderRefund exampleOrderRefund = new OrderRefund();
        exampleOrderRefund.setRefundNo(refundNo);
        exampleOrderRefund.setStatus(KmallStatusConstant.NORMAL);
        return orderRefundRepository.findOne(Example.of(exampleOrderRefund)).orElseThrow(() -> new ServiceException(KmallResultEnum.ORDER_REFUND_FAIL));
    }

    /**
     * 更新退款单
     * @param orderRefund 退款单
     */
    @Override
    public void update(OrderRefund orderRefund) {
        orderRefundRepository.update(orderRefund);
    }

    /**
     * 生成订单号
     * @return 订单号
     */
    private String createOrderRefundNo() {
        LocalDateTime dateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
        Random rand = new Random();
        int j = rand.nextInt(10);
        int k = rand.nextInt(10);
        String orderNo = 9 + dateTime.format(formatter) + j + k;
        return orderNo;
    }
}
